import React, { useState, useEffect, useRef } from "react";
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Space,
  Table,
  Tag,
  Modal,
  message,
  Row,
  Col,
  Divider,
  Typography,
  Tooltip,
  Progress,
  List,
  Avatar,
  Drawer,
  Steps,
  Alert,
  Collapse,
  Timeline,
  Badge,
  Tabs,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SaveOutlined,
  RobotOutlined,
  EyeOutlined,
  CopyOutlined,
  FileTextOutlined,
  BookOutlined,
  BulbOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ShareAltOutlined,
  HistoryOutlined,
  StarOutlined,
  TeamOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import { aiService } from "../../../services/ai";

const { TextArea } = Input;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;
const { TabPane } = Tabs;
const { Step } = Steps;

// 样式组件
const PreparationContainer = styled.div`
  padding: 24px;
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const AIAssistantPanel = styled.div`
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
`;

const LessonCard = styled(Card)`
  margin-bottom: 16px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
`;

const StatusTag = styled(Tag)<{ status: string }>`
  ${(props) => {
    switch (props.status) {
      case "draft":
        return "border-color: #faad14; color: #faad14; background: #fff7e6;";
      case "completed":
        return "border-color: #52c41a; color: #52c41a; background: #f6ffed;";
      case "published":
        return "border-color: #1890ff; color: #1890ff; background: #e6f7ff;";
      default:
        return "";
    }
  }}
`;

// 接口定义
interface LessonPlan {
  id: string;
  title: string;
  subject: string;
  courseId?: string;
  courseName?: string;
  status: "draft" | "completed" | "published";
  content: LessonContent;
  aiSuggestions: AISuggestion[];
  autoSaveTime: Date;
  createTime: Date;
  updateTime: Date;
  author: string;
  tags: string[];
  duration: number; // 课时长度（分钟）
  targetGrade: string;
  difficulty: "easy" | "medium" | "hard";
  objectives: string[];
  resources: Resource[];
  isShared: boolean;
  sharedBy?: string;
  favorites: number;
}

interface LessonContent {
  introduction: string;
  objectives: string[];
  keyPoints: string[];
  difficulties: string[];
  teachingMethods: string[];
  activities: Activity[];
  assessment: string;
  homework: string;
  reflection: string;
}

interface Activity {
  id: string;
  name: string;
  description: string;
  duration: number;
  type: "lecture" | "discussion" | "practice" | "experiment" | "presentation";
  materials: string[];
}

interface AISuggestion {
  id: string;
  type: "content" | "method" | "activity" | "assessment";
  title: string;
  description: string;
  confidence: number;
}

interface Resource {
  id: string;
  name: string;
  type: "ppt" | "video" | "document" | "link" | "image";
  url: string;
  size?: number;
}

interface LessonTemplate {
  id: string;
  name: string;
  description: string;
  subject: string;
  targetGrade: string;
  structure: LessonContent;
  tags: string[];
  downloads: number;
  rating: number;
  author: string;
}

const LessonPreparation: React.FC = () => {
  // 状态管理
  const [lessonPlans, setLessonPlans] = useState<LessonPlan[]>([]);
  const [templates, setTemplates] = useState<LessonTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPlan, setCurrentPlan] = useState<LessonPlan | null>(null);

  // 模态框状态
  const [editorVisible, setEditorVisible] = useState(false);
  const [templateVisible, setTemplateVisible] = useState(false);
  const [libraryVisible, setLibraryVisible] = useState(false);

  // AI相关状态
  const [aiLoading, setAiLoading] = useState(false);
  const [aiSuggestions, setAiSuggestions] = useState<AISuggestion[]>([]);

  // 表单
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 自动保存定时器
  const autoSaveTimer = useRef<NodeJS.Timeout | null>(null);

  // 初始化数据
  useEffect(() => {
    loadLessonPlans();
    loadTemplates();
  }, []);

  // 加载备课计划列表
  const loadLessonPlans = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      const mockPlans: LessonPlan[] = [
        {
          id: "1",
          title: "React组件设计与开发",
          subject: "前端开发",
          courseName: "Web前端技术",
          status: "draft",
          content: {
            introduction: "本节课将学习React组件的设计原则和开发实践",
            objectives: [
              "掌握组件设计原则",
              "学会函数组件和类组件",
              "理解props和state",
            ],
            keyPoints: ["组件化思想", "生命周期", "状态管理"],
            difficulties: ["生命周期理解", "状态提升"],
            teachingMethods: ["讲授法", "演示法", "实践法"],
            activities: [
              {
                id: "a1",
                name: "理论讲解",
                description: "介绍React组件基础概念",
                duration: 30,
                type: "lecture",
                materials: ["PPT", "示例代码"],
              },
              {
                id: "a2",
                name: "实践练习",
                description: "创建第一个React组件",
                duration: 45,
                type: "practice",
                materials: ["在线编辑器", "练习题"],
              },
            ],
            assessment: "课堂练习 + 作业完成情况",
            homework: "创建一个包含多个组件的小项目",
            reflection: "",
          },
          aiSuggestions: [],
          autoSaveTime: new Date(),
          createTime: new Date(),
          updateTime: new Date(),
          author: "张老师",
          tags: ["React", "前端", "组件"],
          duration: 90,
          targetGrade: "大二",
          difficulty: "medium",
          objectives: ["掌握React组件开发"],
          resources: [],
          isShared: false,
          favorites: 0,
        },
        // 更多模拟数据...
      ];

      setLessonPlans(mockPlans);
    } catch (error) {
      message.error("加载备课计划失败");
    } finally {
      setLoading(false);
    }
  };

  // 加载模板库
  const loadTemplates = async () => {
    try {
      const mockTemplates: LessonTemplate[] = [
        {
          id: "t1",
          name: "程序设计基础课模板",
          description: "适用于编程类课程的通用模板",
          subject: "计算机科学",
          targetGrade: "大一",
          structure: {
            introduction: "课程导入...",
            objectives: ["知识目标", "能力目标", "素质目标"],
            keyPoints: ["重点1", "重点2"],
            difficulties: ["难点1", "难点2"],
            teachingMethods: ["讲授法", "演示法", "实验法"],
            activities: [],
            assessment: "形成性评价 + 终结性评价",
            homework: "编程练习",
            reflection: "教学反思",
          },
          tags: ["编程", "基础", "通用"],
          downloads: 1250,
          rating: 4.8,
          author: "系统模板",
        },
        // 更多模板...
      ];

      setTemplates(mockTemplates);
    } catch (error) {
      message.error("加载模板库失败");
    }
  };

  // 创建新的备课计划
  const createNewPlan = () => {
    const newPlan: LessonPlan = {
      id: Date.now().toString(),
      title: "新的备课计划",
      subject: "",
      status: "draft",
      content: {
        introduction: "",
        objectives: [],
        keyPoints: [],
        difficulties: [],
        teachingMethods: [],
        activities: [],
        assessment: "",
        homework: "",
        reflection: "",
      },
      aiSuggestions: [],
      autoSaveTime: new Date(),
      createTime: new Date(),
      updateTime: new Date(),
      author: "当前用户",
      tags: [],
      duration: 90,
      targetGrade: "大二",
      difficulty: "medium",
      objectives: [],
      resources: [],
      isShared: false,
      favorites: 0,
    };

    setCurrentPlan(newPlan);
    form.setFieldsValue(newPlan);
    setEditorVisible(true);
  };

  // 编辑备课计划
  const editPlan = (plan: LessonPlan) => {
    setCurrentPlan(plan);
    form.setFieldsValue(plan);
    setEditorVisible(true);
  };

  // 自动保存功能
  const startAutoSave = () => {
    if (autoSaveTimer.current) {
      clearInterval(autoSaveTimer.current);
    }

    autoSaveTimer.current = setInterval(() => {
      if (currentPlan) {
        handleAutoSave();
      }
    }, 30000); // 30秒自动保存一次
  };

  const handleAutoSave = async () => {
    try {
      const values = await form.getFieldsValue();
      const updatedPlan = {
        ...currentPlan!,
        ...values,
        autoSaveTime: new Date(),
      };

      // 模拟API保存
      await new Promise((resolve) => setTimeout(resolve, 500));

      setCurrentPlan(updatedPlan);
      message.success("自动保存成功", 1);
    } catch (error) {
      console.error("自动保存失败:", error);
    }
  };

  // 手动保存
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const updatedPlan = {
        ...currentPlan!,
        ...values,
        updateTime: new Date(),
      };

      setLoading(true);
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 更新列表
      setLessonPlans((prev) => {
        const index = prev.findIndex((p) => p.id === updatedPlan.id);
        if (index >= 0) {
          const newList = [...prev];
          newList[index] = updatedPlan;
          return newList;
        } else {
          return [updatedPlan, ...prev];
        }
      });

      setCurrentPlan(updatedPlan);
      message.success("保存成功");
    } catch (error) {
      message.error("保存失败");
    } finally {
      setLoading(false);
    }
  };

  // AI辅助生成内容
  const handleAIGenerate = async (
    type: "full" | "objectives" | "activities" | "assessment"
  ) => {
    setAiLoading(true);
    try {
      const values = form.getFieldsValue();
      const courseData = {
        subject: values.subject || "计算机科学",
        topic: values.title || "课程主题",
        duration: values.duration || 90,
        targetGrade: values.targetGrade || "大二",
        objectives: values.objectives || [],
      };

      const response = await aiService.generateLessonPlan(courseData);

      // 模拟AI生成的内容
      const aiContent = {
        objectives: [
          "掌握核心概念和基本原理",
          "培养实际应用能力",
          "提升问题解决思维",
        ],
        keyPoints: ["重要概念理解", "实践操作技能", "案例分析方法"],
        activities: [
          {
            id: Date.now().toString(),
            name: "概念讲解",
            description: "系统介绍核心概念",
            duration: 30,
            type: "lecture" as const,
            materials: ["PPT", "教材"],
          },
          {
            id: (Date.now() + 1).toString(),
            name: "实践练习",
            description: "动手操作和练习",
            duration: 45,
            type: "practice" as const,
            materials: ["练习题", "实验环境"],
          },
        ],
        assessment: "过程性评价与结果性评价相结合",
      };

      // 根据类型更新对应字段
      if (type === "full") {
        form.setFieldsValue({
          content: {
            ...form.getFieldValue("content"),
            ...aiContent,
          },
        });
      } else if (type === "objectives") {
        form.setFieldValue(["content", "objectives"], aiContent.objectives);
      } else if (type === "activities") {
        form.setFieldValue(["content", "activities"], aiContent.activities);
      } else if (type === "assessment") {
        form.setFieldValue(["content", "assessment"], aiContent.assessment);
      }

      // 生成AI建议
      const suggestions: AISuggestion[] = [
        {
          id: "s1",
          type: "method",
          title: "建议使用案例教学法",
          description: "结合实际案例可以提高学生的理解和兴趣",
          confidence: 85,
        },
        {
          id: "s2",
          type: "activity",
          title: "增加小组讨论环节",
          description: "促进学生交流和思考，提升课堂互动性",
          confidence: 78,
        },
      ];

      setAiSuggestions(suggestions);
      message.success("AI内容生成成功！");
    } catch (error) {
      message.error("AI生成失败，请重试");
    } finally {
      setAiLoading(false);
    }
  };

  // 从模板创建
  const createFromTemplate = (template: LessonTemplate) => {
    const newPlan: LessonPlan = {
      id: Date.now().toString(),
      title: `基于${template.name}的新备课`,
      subject: template.subject,
      status: "draft",
      content: { ...template.structure },
      aiSuggestions: [],
      autoSaveTime: new Date(),
      createTime: new Date(),
      updateTime: new Date(),
      author: "当前用户",
      tags: [...template.tags],
      duration: 90,
      targetGrade: template.targetGrade,
      difficulty: "medium",
      objectives: template.structure.objectives,
      resources: [],
      isShared: false,
      favorites: 0,
    };

    setCurrentPlan(newPlan);
    form.setFieldsValue(newPlan);
    setTemplateVisible(false);
    setEditorVisible(true);
    message.success("已从模板创建新的备课计划");
  };

  // 开始编辑时启动自动保存
  useEffect(() => {
    if (editorVisible && currentPlan) {
      startAutoSave();
    }

    return () => {
      if (autoSaveTimer.current) {
        clearInterval(autoSaveTimer.current);
      }
    };
  }, [editorVisible, currentPlan]);

  // 备课计划列表表格列定义
  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      ellipsis: true,
    },
    {
      title: "学科",
      dataIndex: "subject",
      key: "subject",
      width: 100,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      render: (status: string) => {
        const statusMap = {
          draft: { text: "草稿", color: "orange" },
          completed: { text: "已完成", color: "green" },
          published: { text: "已发布", color: "blue" },
        };
        const config = statusMap[status as keyof typeof statusMap];
        return <StatusTag status={status}>{config.text}</StatusTag>;
      },
    },
    {
      title: "课时",
      dataIndex: "duration",
      key: "duration",
      width: 80,
      render: (duration: number) => `${duration}分钟`,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
      width: 120,
      render: (time: Date) => time.toLocaleDateString(),
    },
    {
      title: "操作",
      key: "actions",
      width: 200,
      render: (_: any, record: LessonPlan) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => editPlan(record)}
            />
          </Tooltip>
          <Tooltip title="预览">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => {
                setCurrentPlan(record);
                setLibraryVisible(true);
              }}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button
              type="link"
              size="small"
              icon={<CopyOutlined />}
              onClick={() => {
                const newPlan = {
                  ...record,
                  id: Date.now().toString(),
                  title: `${record.title} - 副本`,
                  status: "draft" as const,
                  createTime: new Date(),
                };
                setLessonPlans((prev) => [newPlan, ...prev]);
                message.success("复制成功");
              }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: "确认删除",
                  content: "确定要删除这个备课计划吗？",
                  onOk: () => {
                    setLessonPlans((prev) =>
                      prev.filter((p) => p.id !== record.id)
                    );
                    message.success("删除成功");
                  },
                });
              }}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <PreparationContainer>
      {/* 顶部工具栏 */}
      <StyledCard>
        <Row gutter={16} align="middle">
          <Col span={18}>
            <Form form={searchForm} layout="inline">
              <Form.Item name="keyword">
                <Input
                  placeholder="搜索备课计划..."
                  allowClear
                  style={{ width: 250 }}
                />
              </Form.Item>
              <Form.Item name="subject">
                <Select placeholder="学科" allowClear style={{ width: 120 }}>
                  <Option value="计算机科学">计算机科学</Option>
                  <Option value="数学">数学</Option>
                  <Option value="物理">物理</Option>
                </Select>
              </Form.Item>
              <Form.Item name="status">
                <Select placeholder="状态" allowClear style={{ width: 100 }}>
                  <Option value="draft">草稿</Option>
                  <Option value="completed">已完成</Option>
                  <Option value="published">已发布</Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
              </Form.Item>
            </Form>
          </Col>
          <Col span={6} style={{ textAlign: "right" }}>
            <Space>
              <Button
                icon={<BookOutlined />}
                onClick={() => setTemplateVisible(true)}
              >
                备课库
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={createNewPlan}
              >
                新建备课
              </Button>
            </Space>
          </Col>
        </Row>
      </StyledCard>

      {/* 备课计划列表 */}
      <StyledCard title="我的备课计划">
        <Table
          columns={columns}
          dataSource={lessonPlans}
          rowKey="id"
          loading={loading}
          pagination={{
            total: lessonPlans.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </StyledCard>

      {/* 备课编辑器 */}
      <Drawer
        title={
          <Space>
            <FileTextOutlined />
            <span>{currentPlan?.title || "新建备课"}</span>
            {currentPlan?.autoSaveTime && (
              <Text type="secondary" style={{ fontSize: 12 }}>
                自动保存于 {currentPlan.autoSaveTime.toLocaleTimeString()}
              </Text>
            )}
          </Space>
        }
        placement="right"
        width="80%"
        open={editorVisible}
        onClose={() => setEditorVisible(false)}
        extra={
          <Space>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              onClick={handleSave}
              loading={loading}
            >
              保存
            </Button>
            <Button
              icon={<RobotOutlined />}
              onClick={() => handleAIGenerate("full")}
              loading={aiLoading}
            >
              AI辅助
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          {/* 基本信息 */}
          <Card title="基本信息" size="small" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="title"
                  label="课程标题"
                  rules={[{ required: true, message: "请输入课程标题" }]}
                >
                  <Input placeholder="请输入课程标题" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="subject"
                  label="学科"
                  rules={[{ required: true, message: "请选择学科" }]}
                >
                  <Select placeholder="请选择学科">
                    <Option value="计算机科学">计算机科学</Option>
                    <Option value="数学">数学</Option>
                    <Option value="物理">物理</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item name="targetGrade" label="目标年级">
                  <Select placeholder="选择年级">
                    <Option value="大一">大一</Option>
                    <Option value="大二">大二</Option>
                    <Option value="大三">大三</Option>
                    <Option value="大四">大四</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="duration" label="课时长度（分钟）">
                  <InputNumber min={30} max={180} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="difficulty" label="难度等级">
                  <Select placeholder="选择难度">
                    <Option value="easy">简单</Option>
                    <Option value="medium">中等</Option>
                    <Option value="hard">困难</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </Card>

          {/* AI建议面板 */}
          {aiSuggestions.length > 0 && (
            <AIAssistantPanel>
              <Title level={5} style={{ color: "white", marginBottom: 16 }}>
                <RobotOutlined /> AI智能建议
              </Title>
              <List
                dataSource={aiSuggestions}
                renderItem={(suggestion) => (
                  <List.Item style={{ borderColor: "rgba(255,255,255,0.2)" }}>
                    <List.Item.Meta
                      avatar={<BulbOutlined style={{ color: "white" }} />}
                      title={
                        <span style={{ color: "white" }}>
                          {suggestion.title}
                          <Badge
                            count={`${suggestion.confidence}%`}
                            style={{ marginLeft: 8 }}
                          />
                        </span>
                      }
                      description={
                        <span style={{ color: "rgba(255,255,255,0.8)" }}>
                          {suggestion.description}
                        </span>
                      }
                    />
                  </List.Item>
                )}
              />
            </AIAssistantPanel>
          )}

          {/* 课程内容 */}
          <Tabs defaultActiveKey="basic">
            <TabPane tab="基础内容" key="basic">
              <Space direction="vertical" style={{ width: "100%" }}>
                <Form.Item name={["content", "introduction"]} label="课程导入">
                  <TextArea rows={3} placeholder="请描述课程导入内容..." />
                </Form.Item>

                <Form.Item
                  name={["content", "objectives"]}
                  label={
                    <Space>
                      <span>教学目标</span>
                      <Button
                        type="link"
                        size="small"
                        icon={<RobotOutlined />}
                        onClick={() => handleAIGenerate("objectives")}
                        loading={aiLoading}
                      >
                        AI生成
                      </Button>
                    </Space>
                  }
                >
                  <Select
                    mode="tags"
                    placeholder="请输入教学目标，支持多个"
                    style={{ width: "100%" }}
                  />
                </Form.Item>

                <Form.Item name={["content", "keyPoints"]} label="教学重点">
                  <Select
                    mode="tags"
                    placeholder="请输入教学重点，支持多个"
                    style={{ width: "100%" }}
                  />
                </Form.Item>

                <Form.Item name={["content", "difficulties"]} label="教学难点">
                  <Select
                    mode="tags"
                    placeholder="请输入教学难点，支持多个"
                    style={{ width: "100%" }}
                  />
                </Form.Item>
              </Space>
            </TabPane>

            <TabPane tab="教学设计" key="design">
              <Space direction="vertical" style={{ width: "100%" }}>
                <Form.Item
                  name={["content", "teachingMethods"]}
                  label="教学方法"
                >
                  <Select
                    mode="multiple"
                    placeholder="选择教学方法"
                    style={{ width: "100%" }}
                  >
                    <Option value="讲授法">讲授法</Option>
                    <Option value="演示法">演示法</Option>
                    <Option value="讨论法">讨论法</Option>
                    <Option value="实验法">实验法</Option>
                    <Option value="案例法">案例法</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label={
                    <Space>
                      <span>教学活动</span>
                      <Button
                        type="link"
                        size="small"
                        icon={<RobotOutlined />}
                        onClick={() => handleAIGenerate("activities")}
                        loading={aiLoading}
                      >
                        AI生成
                      </Button>
                    </Space>
                  }
                >
                  <Card size="small">
                    <Timeline>
                      <Timeline.Item color="blue">
                        <Space>
                          <ClockCircleOutlined />
                          <span>课程导入 (10分钟)</span>
                        </Space>
                      </Timeline.Item>
                      <Timeline.Item color="green">
                        <Space>
                          <BookOutlined />
                          <span>知识讲解 (40分钟)</span>
                        </Space>
                      </Timeline.Item>
                      <Timeline.Item color="orange">
                        <Space>
                          <TeamOutlined />
                          <span>实践练习 (30分钟)</span>
                        </Space>
                      </Timeline.Item>
                      <Timeline.Item color="purple">
                        <Space>
                          <CheckCircleOutlined />
                          <span>总结回顾 (10分钟)</span>
                        </Space>
                      </Timeline.Item>
                    </Timeline>
                  </Card>
                </Form.Item>
              </Space>
            </TabPane>

            <TabPane tab="评估作业" key="assessment">
              <Space direction="vertical" style={{ width: "100%" }}>
                <Form.Item
                  name={["content", "assessment"]}
                  label={
                    <Space>
                      <span>评估方式</span>
                      <Button
                        type="link"
                        size="small"
                        icon={<RobotOutlined />}
                        onClick={() => handleAIGenerate("assessment")}
                        loading={aiLoading}
                      >
                        AI建议
                      </Button>
                    </Space>
                  }
                >
                  <TextArea rows={3} placeholder="请描述评估方式和标准..." />
                </Form.Item>

                <Form.Item name={["content", "homework"]} label="课后作业">
                  <TextArea
                    rows={4}
                    placeholder="请描述课后作业内容和要求..."
                  />
                </Form.Item>

                <Form.Item name={["content", "reflection"]} label="教学反思">
                  <TextArea rows={3} placeholder="课后可补充教学反思..." />
                </Form.Item>
              </Space>
            </TabPane>
          </Tabs>
        </Form>
      </Drawer>

      {/* 备课库模态框 */}
      <Modal
        title={
          <Space>
            <BookOutlined />
            <span>备课模板库</span>
          </Space>
        }
        open={templateVisible}
        onCancel={() => setTemplateVisible(false)}
        width={1000}
        footer={null}
      >
        <Row gutter={[16, 16]}>
          {templates.map((template) => (
            <Col span={12} key={template.id}>
              <LessonCard>
                <Card.Meta
                  avatar={<Avatar icon={<FileTextOutlined />} />}
                  title={
                    <Space>
                      <span>{template.name}</span>
                      <Space>
                        <Tag color="blue">{template.subject}</Tag>
                        <Tag color="green">{template.targetGrade}</Tag>
                      </Space>
                    </Space>
                  }
                  description={template.description}
                />
                <div style={{ marginTop: 16 }}>
                  <Space split={<Divider type="vertical" />}>
                    <span>
                      <StarOutlined /> {template.rating}
                    </span>
                    <span>
                      <DownloadOutlined /> {template.downloads}
                    </span>
                    <span>作者: {template.author}</span>
                  </Space>
                  <div style={{ marginTop: 8, textAlign: "right" }}>
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => createFromTemplate(template)}
                    >
                      使用模板
                    </Button>
                  </div>
                </div>
              </LessonCard>
            </Col>
          ))}
        </Row>
      </Modal>

      {/* 预览抽屉 */}
      <Drawer
        title="备课计划预览"
        placement="right"
        width="60%"
        open={libraryVisible}
        onClose={() => setLibraryVisible(false)}
      >
        {currentPlan && (
          <div>
            <Title level={3}>{currentPlan.title}</Title>
            <Space wrap style={{ marginBottom: 24 }}>
              <Tag color="blue">{currentPlan.subject}</Tag>
              <Tag color="green">{currentPlan.targetGrade}</Tag>
              <Tag color="orange">{currentPlan.duration}分钟</Tag>
              <StatusTag status={currentPlan.status}>
                {currentPlan.status === "draft"
                  ? "草稿"
                  : currentPlan.status === "completed"
                    ? "已完成"
                    : "已发布"}
              </StatusTag>
            </Space>

            <Collapse defaultActiveKey={["1", "2"]}>
              <Panel header="教学目标" key="1">
                <List
                  dataSource={currentPlan.content.objectives}
                  renderItem={(item) => (
                    <List.Item>
                      <CheckCircleOutlined
                        style={{ color: "#52c41a", marginRight: 8 }}
                      />
                      {item}
                    </List.Item>
                  )}
                />
              </Panel>

              <Panel header="教学重难点" key="2">
                <Row gutter={16}>
                  <Col span={12}>
                    <Title level={5}>重点</Title>
                    <List
                      dataSource={currentPlan.content.keyPoints}
                      renderItem={(item) => <List.Item>{item}</List.Item>}
                    />
                  </Col>
                  <Col span={12}>
                    <Title level={5}>难点</Title>
                    <List
                      dataSource={currentPlan.content.difficulties}
                      renderItem={(item) => <List.Item>{item}</List.Item>}
                    />
                  </Col>
                </Row>
              </Panel>

              <Panel header="教学设计" key="3">
                <Paragraph>{currentPlan.content.introduction}</Paragraph>
                <Title level={5}>教学方法</Title>
                <Space wrap>
                  {currentPlan.content.teachingMethods.map((method, index) => (
                    <Tag key={index} color="blue">
                      {method}
                    </Tag>
                  ))}
                </Space>
              </Panel>

              <Panel header="评估与作业" key="4">
                <Title level={5}>评估方式</Title>
                <Paragraph>{currentPlan.content.assessment}</Paragraph>
                <Title level={5}>课后作业</Title>
                <Paragraph>{currentPlan.content.homework}</Paragraph>
              </Panel>
            </Collapse>
          </div>
        )}
      </Drawer>
    </PreparationContainer>
  );
};

export default LessonPreparation;
